<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model
{
    //add answer
    public function add()
    {
        if (!user_ins()->is_logged_in())
            return ['status' => 0, 'msg' => 'no login'];

        if (!rq('question_id') || !rq('content'))
            return ['status' => 0, 'msg' => 'need question_id&content '];

        $question = question_ins()->where(['id' => rq('question_id'), 'status' => 'ok'])->get()->toArray();
        if (!$question)
            return ['status' => 0, 'msg' => 'no question'];

        $r = $this->where(['question_id' => rq('question_id'), 'user_id' => session('user_id')])->count();
        if ($r)
            return ['status' => 0, 'msg' => 'has answered'];

        $this->content = rq('content');
        $this->question_id = rq('question_id');
        $this->user_id = session('user_id');

        return $this->save() ?
            ['status' => 200] :
            ['status' => 0, 'msg' => 'save failed'];

    }

    //change answer
    public function change()
    {
        if (!user_ins()->is_logged_in())
            return ['status' => 0, 'msg' => 'no login'];

        if (!rq('id') || !rq('content'))
            return ['status' => 0, 'msg' => 'no id&content'];

        $answer = $this->find(rq('id'));
        if (empty($answer))
            return ['status' => 0, 'msg' => 'no fund answer'];

        if ($answer->user_id != session('user_id'))
            return ['status' => 0, 'msg' => 'no auth'];

        $answer->content = rq('content');
        return $answer->save() ?
            ['status' => 200] :
            ['status' => 0, 'msg' => 'change failed'];
    }

    //read  answer
    public function read()
    {
        if (!rq('id') && !rq('question_id') && !rq('user_id'))
            return ['status' => 0, 'msg' => 'id || question_id required'];

        $user_id = rq('user_id');
        if ($user_id) {

            if ($user_id === 'self')
                $user_id = session('user_id');

            return $this->read_by_user_id($user_id);
        }
        //单个回答
        if (rq('id')) {
            $answer = $this
                ->with('user')
                ->with('users')
                ->find(rq('id'));
            if (!$answer)
                return ['status' => 0, 'msg' => 'answer not exists'];
            //计算赞和踩
            $answer = $this->count_vote($answer->toArray());
            return ['status' => 200, 'data' => $answer];
        }
        //check问题是否存在
        if (!question_ins()->find(rq('question_id')))
            return ['status' => 0, 'msg' => 'question not exists'];
        //单个问题所有回答
        $answers = $this->where('question_id', rq('question_id'))
            ->get()
            ->keyBy('id');

        return ['status' => 200, 'data' => $answers];
    }

    public function read_by_user_id($user_id)
    {

        $user = user_ins()->find($user_id);
        if (!$user)
            return err('user_id error');

        $r = $this
            ->with('question')
            ->where('user_id', $user_id)->get()->keyBy('id')->toArray();

        return suc(['data' => $r]);
    }

    public function vote()
    {
        if (!user_ins()->is_logged_in())
            return ['status' => 0, 'msg' => 'no login'];

        if (!rq('id') || !rq('vote'))
            return ['status' => 0, 'msg' => 'id&vote not require'];

        $answer = $this->find(rq('id'));
        /*1赞 2踩 3清空*/
        $vote = rq('vote');
        if (!in_array($vote, [1, 2, 3])) {
            return err('vote error');
        }
        if (!$answer)
            return ['status' => 0, 'msg' => 'answer not exists'];
        //检查用户是否在相同评论下同时点了 赞和反对
        $answer->users()
            ->newPivotStatement()
            ->where('user_id', session('user_id'))
            ->where('answer_id', rq('id'))
            ->delete();
        if ($vote == 3) {
            return suc();
        }
        //存储
        $answer->users()
            ->attach(session('user_id'), ['vote' => $vote]);
        return ['status' => 200, 'data' => $answer];
    }

    public function users()
    {
        return $this->belongsToMany('App\User')
            ->withPivot('vote')
            ->withTimestamps();
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function question()
    {
        return $this->belongsTo('App\Question');
    }

    public function count_vote($answer)
    {

        foreach ($answer['users'] as $user) {
            $answer['upvote_count'] = 0;
            $answer['downvote_count'] = 0;

            if ($user['pivot']['vote'] == 1) {
                $answer['upvote_count']++;
            }
            if ($user['pivot']['vote'] == 2) {
                $answer['downvote_count']++;
            }
        }
        return $answer;
    }
}
